package reviewAlgorithms.search;

import java.util.HashSet;
import java.util.Set;

public class NumSquares4 {
    public static void main(String[] args) {
        int num = 12;
        System.out.println(numSquare(num));
    }

    private static int numSquare(int num) {
        if (num < 1){
            return 0;
        }
        Set<Integer> square = new HashSet<>();
        for (int i = 1; i * i < num; i++) {
            square.add(i * i);
        }
        Set<Integer> set = new HashSet<>();
        Set<Integer> setTemp = new HashSet<>();
        set.add(num);
        int count = 1;
        while (!set.isEmpty()){
            for (Integer item: set) {
                if (square.contains(item)){
                    return count;
                }
            }
            for (Integer item : set) {
                int i = 1;
                while (i * i < item){
                    setTemp.add(item - i * i);
                    i ++;
                }
            }
            set.clear();
            set.addAll(setTemp);
            setTemp.clear();
            count ++;
        }
        return count;
    }
}
